<template>
  <!-- <div @click="showDate = true">{{ showName }}<van-icon name="arrow-down" class="d-mg-l5" /></div> -->
  <SelectBlock @click="showDate = true" :text="showName" />

  <van-popup v-model:show="showDate" round position="bottom" :teleport="body">
    <van-date-picker v-model="date" @cancel="showDate = false" @confirm="onConfirm" :columns-type="['year', 'month']"
      :formatter="formatter" :max-date="maxDate" />
  </van-popup>
</template>

<script setup>

import { onMounted, ref, watch } from 'vue'
import SelectBlock from '../basic-components/SelectBlock.vue'

/** 选择 年、月份 */

const props = defineProps(['modelValue'])
const emits = defineEmits(['update:modelValue', 'confirm'])

const maxDate = ref(null);

const body = document.body

const showDate = ref(false)

const date = ref([''])

const today = new Date()
const currentYear = today.getFullYear().toString()
const currentMonth = ('0' + (today.getMonth() + 1)).slice(-2)
const showName = ref(`${currentYear}年${currentMonth}月`)

const onConfirm = value => {
  const selectedYear = value.selectedValues[0]
  const selectedMonth = ('0' + value.selectedValues[1]).slice(-2)
  showName.value = `${selectedYear}年${selectedMonth}月`
  showDate.value = false
  const modelValue = [selectedYear, selectedMonth]
  emits('update:modelValue', modelValue)
  emits('confirm', modelValue)
}

const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  return option;
}

onMounted(() => {
  // 设置 maxDate 为当前日期
  maxDate.value = today;

  if (props.modelValue && props.modelValue.length > 0) {
    const [year, month] = props.modelValue
    date.value = [year, month]
    showName.value = `${year}年${month}月`
  } else {
    const cy = today.getFullYear() + ''
    const cm = ('0' + (today.getMonth() + 1)).slice(-2)
    date.value = [cy, cm]
    showName.value = `${cy}年${cm}月`
  }
});

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      const [year, month] = newVal
      date.value = [year, month]
      showName.value = `${year}年${month}月`
    } else {
      const today = new Date()
      const cy = today.getFullYear() + ''
      const cm = ('0' + (today.getMonth() + 1)).slice(-2)
      date.value = [cy, cm]
      showName.value = `${cy}年${cm}月`
    }
  }
)

</script>

<style lang="scss" scoped></style>